//
//  KY1000AdvertView.m
//  KYMobClick
//
//  Created by 01 on 16/11/8.
//  Copyright © 2016年 Czj. All rights reserved.
//

#import "KY1000AdvertView.h"
static int startViewDismissTimeInterval = 5;

@interface KY1000AdvertView ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) CGFloat playTime;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) NSMutableDictionary *dict;
@property (nonatomic, strong) KYLoopProgressView *loopProgressView;
@property (nonatomic, strong) UIWindow *window;
@end

@implementation KY1000AdvertView

#pragma mark - Init
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
    self.displayLink.paused = YES;
    [self.displayLink invalidate];
    self.displayLink = nil;
}

#pragma mark - Public methods
/**
 接收数据填充视图
 */
- (void)createContent:(NSDictionary *)dataDic blockLoadSuccess:(void (^)())blockLoadSuccess {
    self.dict = [NSMutableDictionary dictionaryWithDictionary:dataDic];
    self.backgroundColor = [UIColor greenColor];
    [self creatView];
    [self show];
    [self createTimer];
    [self creatDisPlayLink];
    if (blockLoadSuccess) blockLoadSuccess();
}

#pragma mark - Private methods
- (void)creatView{
    //初始化一个Window， 做到对业务视图无干扰。
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.rootViewController = [[UIViewController alloc] init];
    window.rootViewController.view.backgroundColor = [UIColor clearColor];
    window.rootViewController.view.userInteractionEnabled = NO;
    self.window = window;
    
    //创建广告视图和宣传视图
    UIImageView *advertImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
    advertImgView.userInteractionEnabled = YES;
    
    UIImageView *propagandaImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(advertImgView.frame), kDeviceWidth, kCurrentScreenWidth(107.5))];
    propagandaImgView.userInteractionEnabled = YES;
    if (self.dict && self.dict[@"data"]) {
        NSString *pathDocument = [KYSystemInfo getSaveAdvertImagePath];
        NSString *imagePath = [pathDocument stringByAppendingString:[NSString stringWithFormat:@"%@.png",self.dict[@"data"][@"adsid"]]];
        UIImage *cacheImage = [UIImage imageWithContentsOfFile:imagePath]?[UIImage imageWithContentsOfFile:imagePath]:[UIImage ky_imageWithColor:[UIColor whiteColor]];
        [advertImgView KYSD_setImageWithURL:[NSURL URLWithString:self.dict[@"data"][@"imageurl"]] placeholderImage:cacheImage options:kNilOptions completed:^(UIImage *image, NSError *error, KYSDImageCacheType cacheType, NSURL *imageURL) {
            [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
            [self postPVData];
        }];
        [propagandaImgView KYSD_setImageWithURL:[NSURL URLWithString:self.dict[@"data"][@"app_ads"]] placeholderImage:[UIImage ky_imageWithColor:[UIColor whiteColor]]];
    }
    [window addSubview:advertImgView];
    [window addSubview:propagandaImgView];
    
    //添加倒计时视图
    self.loopProgressView.userInteractionEnabled = YES;
    [window addSubview:self.loopProgressView];
    
    //创建点击广告手势、宣传图手势和跳过按钮手势
    UITapGestureRecognizer *advertTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeAdvertPage)];
    [advertImgView addGestureRecognizer:advertTap];
    
    UITapGestureRecognizer *propagandaImgTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeAdvertPage)];
    [propagandaImgView addGestureRecognizer:propagandaImgTap];
    
    UITapGestureRecognizer *skipTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endCurrentPage)];
    [self.loopProgressView addGestureRecognizer:skipTap];
}
/**
 展示广告
 */
- (void)show{
    //设置为最顶层，防止 AlertView 等弹窗的覆盖
    self.window.windowLevel = UIWindowLevelStatusBar;
    //默认为YES，当你设置为NO时，这个Window就会显示了
    self.window.hidden = NO;
    self.window.alpha = 1;
}

/**
 隐藏动画
 */
- (void)hide{
    [UIView animateWithDuration:0.1 animations:^{
        self.window.alpha = 0;
    } completion:^(BOOL finished) {
        [self.window.subviews.copy enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        self.window.hidden = YES;
        self.window = nil;
    }];
}
/**
 创建计时器
 */
- (void) createTimer {
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(downloadCurrent) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}
/**
 计时器调用方法
 */
- (void) downloadCurrent {
    startViewDismissTimeInterval--;
    if (startViewDismissTimeInterval < 0) {
        [self endCurrentPage];
    }
//    if (startViewDismissTimeInterval == 2) {
//        [self.dict setObject:@"3" forKey:@"viewTime"];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"advertStatistics" object:self.dict[@"data"]];
//    }
}

/**
 创建DisPlayLink
 */
- (void)creatDisPlayLink {
    self.playTime = 0.0;
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(startAnimate)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

/**
 开始转圈动画
 */
- (void)startAnimate {
    _playTime = _playTime + 1/300.;
    [self.loopProgressView drawProgress:_playTime];
}
/**
 统计PV数据
 */
- (void)postPVData {
    //发送统计数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"advertPVData" object:self.dict[@"data"]];
}
/**
 页面跳转链接
 */
- (void) changeAdvertPage {
//    [self.dict setValue:kOnClick forKey:@"clickStatus"];
    // 提取跳转链接
    NSString *url;
    if (self.dict && self.dict[@"data"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"advertStatistics" object:self.dict[@"data"]];
        url = [NSString stringWithFormat:@"%@",self.dict[@"data"][@"apkurl"]];
    }
    // 广告跳转
    UIViewController* rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
    KYWebViewController *webView = [[KYWebViewController alloc] init];
    webView.urlStr = url;
    webView.dataDict = self.dict;
//    [[rootVC ky_navigationController] pushViewController:webView animated:YES];
    [rootVC presentViewController:webView animated:NO completion:nil];
    [self hide];
}

- (KYLoopProgressView *)loopProgressView {
    if (!_loopProgressView) {
        _loopProgressView = [[KYLoopProgressView alloc] init];
        _loopProgressView.frame = CGRectMake(kDeviceWidth - kCurrentScreenWidth(10) - kCurrentScreenWidth(50), kCurrentScreenWidth(20), kCurrentScreenWidth(50), kCurrentScreenWidth(50));
        _loopProgressView.layer.masksToBounds = YES;
        _loopProgressView.layer.cornerRadius = kCurrentScreenWidth(50)/2.;
    }
    return _loopProgressView;
}

- (void) endCurrentPage {
    [_timer invalidate];
    _timer = nil;
    _displayLink.paused = YES;
    [_displayLink invalidate];
    _displayLink = nil;
    [self hide];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"advertViewEnd" object:nil];
}
@end

@interface KYLoopProgressView()
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@property (nonatomic, strong) UITapGestureRecognizer *skipTap;
@end
@implementation KYLoopProgressView

- (UILabel *)label
{
    if (_label == nil) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2.5, 2.5, self.width - 2.5*2, self.height - 2.5*2)];
        label.textAlignment = NSTextAlignmentCenter;
        label.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
        label.text = @"跳过";
        label.font = kSystemFont(self.width/4.);
        label.textColor = [UIColor whiteColor];
        [self addSubview:label];
        _label = label;
        _label.userInteractionEnabled = YES;
        
    }
    return _label;
}

- (void)drawProgress:(CGFloat )progress
{
    _progress = progress;
    _progressLayer.opacity = 0.1;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    [self drawCycleProgress];
    [self label];
}

- (void)drawCycleProgress {
    CGPoint center = CGPointMake(kCurrentScreenWidth(50)/2., kCurrentScreenWidth(50)/2.);
    CGFloat radius = kCurrentScreenWidth(48)/2.;
    CGFloat startA = - M_PI_2;
    CGFloat endA = -M_PI_2 + M_PI * 2 * _progress;
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = self.bounds;
    _progressLayer.fillColor = [[UIColor clearColor] CGColor];
    _progressLayer.strokeColor = [[UIColor redColor] CGColor];
    _progressLayer.opacity = 1;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.lineWidth = 2.5;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    _progressLayer.path =[path CGPath];
    [self.layer addSublayer:_progressLayer];
}



@end


